<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
	<title>虚拟机模板管理</title>
	<meta name="decorator" content="default"/>
	<link href="${path}/static/uploadify/uploadify.css" rel="stylesheet" type="text/css"/>
	<%--<script type="text/javascript" src="${path}/static/uploadify/jquery-1.8.3.min.js"></script>--%>
	<script type="text/javascript" src="${path}/static/uploadify/swfobject.js"></script>
	<script type="text/javascript" src="${path}/static/uploadify/jquery.uploadify.js"></script>

	<script src="${path}/js/common/jquery.form.js"></script>
	<script type="text/javascript">
		function choose(selete)
		{
			var imageRefObj=document.getElementById("imageRef");
			var imageRefVal=imageRefObj.options[imageRefObj.selectedIndex].value;
			if(imageRefVal==null||imageRefVal=="")
			{
				$("#imageUploadDiv").show();
				document.getElementById("imageName").value="";

			}else{
				$("#imageUploadDiv").hide();

				var text=selete.options[selete.selectedIndex].text;
				document.getElementById("imageName").value=text;
			}





		}

		$('#ram').keyup(function(){
			var c=$(this);
			if(/[^\d]/.test(c.val())){//替换非数字字符
				var temp_amount=c.val().replace(/[^\d]/g,'');
				$(this).val(temp_amount);
			}
		})
		function checkValidate()
		{

			var nameVal=document.getElementById("name").value;
			var imageName=document.getElementById("imageName").value;
			var account=document.getElementById("account").value;
			var password=document.getElementById("password").value;
			var ram=document.getElementById("ram").value;
			var vcpus=document.getElementById("vcpus").value;
			var disk=document.getElementById("disk").value;
			var imageId=document.getElementById("imageId").value;

			var imageRefObj=document.getElementById("imageRef");
			var imageRefVal=imageRefObj.options[imageRefObj.selectedIndex].value;



			//判断是否为空
			if(nameVal==null||nameVal=="")
			{
				alertx("请输入虚拟机模板名称！");
				return false;
			}
			if(imageRefVal==null||imageRefVal=="")
			{
				if(imageId==null||imageId=="")
				{
					alertx("请选择虚拟机镜像或上传镜像！");
					return false;
				}


			}

			if(ram==null||ram=="")
			{
				alertx("请输入内存大小！");
				return false;
			}
			if(vcpus==null||vcpus=="")
			{
				alertx("请输入VCPU数量！");
				return false;
			}
			if(disk==null||disk=="")
			{
				alertx("请输入磁盘大小！");
				return false;
			}
			if(account==null||account=="")
			{
				alertx("请输入账号！");
				return false;
			}
			if(password==null||password=="")
			{
				alertx("请输入密码！");
				return false;
			}

		}
		$(document).ready(function() {

			if("${sceneVmTemplate.imageRef}"!=null&&"${sceneVmTemplate.imageRef}"!='')
			{
				$("#imageUploadDiv").hide();
			}
			$("#inputForm").validate({
				rules: {
					ram: {
						required: true,
						number: true
					},
					vcpus: {
						required: true,
						number: true
					},
					disk: {
						required: true,
						number: true
					}
				},
				submitHandler: function(form){
					loading('正在提交，请稍等...');
					form.submit();
				},
				errorContainer: "#messageBox",
				errorPlacement: function(error, element) {
					$("#messageBox").text("输入有误，请先更正。");
					if (element.is(":checkbox")||element.is(":radio")||element.parent().is(".input-append")){
						error.appendTo(element.parent().parent());
					} else {
						error.insertAfter(element);
					}
				}
			});
		});
		$(function () {
			$("#imageUpload").click(function () {
//				alertx("点击");

				$.jBox($("#importBox").html(), {
					title: "上传镜像", buttons: {"关闭": true},
//					bottomText: "上传文件不能超过10M，仅允许上传“jar”格式文件！",
					loaded: function (e) {
						e.find(".btnImportSubmit").click(function () {

							if (e.find("#uploadFile").val() == "") {
								alertx("请选择镜像上传");
								return false;
							}
							var s = window.parent.document.getElementById("imageMaskDIV");
							s.style.display = "block";
							e.find("#importForm").ajaxSubmit({
								type: "POST",
								dataType: "json",
								url: "${ctx}/scene/sceneVmTemplate/imageUpload",
								success: function (json) {
									if (json.success == true) {
										var fileList = json.dataObj;
										$("#imageName").val(fileList[0]);
										$("#imageUrl").val(fileList[0]);
										$("#imageId").val(fileList[1]);
										alertx("上传镜像成功");
//                                        console.debug( e.parent().next().children("button"));
										e.parent().next().children("button").click();

										var s = window.parent.document.getElementById("imageMaskDIV");
										s.style.display = "none";
									}
									else {
										alertx("上传镜像失败");
										var s = window.parent.document.getElementById("imageMaskDIV");
										s.style.display = "none";
									}
								},
								error: function (XMLHttpRequest, textStatus, errorThrown) {
									alertx("上传镜像失败");
									var s = window.parent.document.getElementById("imageMaskDIV");
									s.style.display = "none";
								}
							});

						})
					}

				});
			});
		});
		function picCheck(selector) {

			var fileName = $(selector).val();

			if (fileName != null && fileName != "") {
				var fileExt = fileName.substr(fileName.lastIndexOf(".")).toLowerCase();
				var fileType1 = new Array(".iso");

				var fileType2 = new Array(".img");

				var fileType3 = new Array(".qcow2");

				var fileType4 = new Array(".vmdk");


				//lastIndexOf如果没有搜索到则返回为-1
				if ($.inArray(fileExt, fileType1) == -1 && $.inArray(fileExt, fileType2) == -1&& $.inArray(fileExt, fileType3) == -1&& $.inArray(fileExt, fileType4) == -1) {
					var file = $(selector);
					file.after(file.clone().val(""));
					file.remove();
					alertx("镜像格式不正确，请上传iso、img、qcow2、vmdk格式");
				}

			}
		}

		$(document).ready(function() {

			$("#uploadify").uploadify({
				'swf': '${path}/static/uploadify/uploadify.swf',
				'uploader' : '${ctx}/scene/sceneVmTemplate/upload',//后台处理的请求
//        'buttonImage' :'/static/uploadify/uploadCancel.png',
				'buttonText' : '选 择 文 件',
				'fileObjName':'file',
				'queueID' : 'fileQueue',//与下面的id对应
				'queueSizeLimit' : 50,    //队列最大长度
				'uploadLimit' : 1,       //一次上传文件数量
				'fileTypeDesc' : '请上传word或pdf文件',
				'fileTypeExts' : '*.iso;*.img;*.qcow2;*.vmdk;', //控制可上传文件的扩展名，启用本项时需同时声明fileDesc
				'auto' : false,             //自动上传
				'multi' : false,              //多文件选择
				'checkExisting' :true,
				'removeTimeout'  :0.4,         //上传成功后到任务自动消失的时间
				'removeCompleted' :true,  //上传完成任务自动消失
				'requeueErrors' :true,
//        'onSelect' :function(file){
//            if(file.size<8000)
//            {
//                alert(file.name+"文件为空");
//
//            }
//        },
				'onUploadSuccess' :function(file,data,response){
					if(data!='')
					{
						$("#imageName").val(file.name);
						document.getElementById("imageId").value=data;    //把获取到的文件ID传值给html
						var tbody = window.document.getElementById("tbody-result");
						var str = "";
						str += "<tr>" +
								"<td>" + file.name + "</td>" +
								"<td><a onclick=deleteFile(\""+ data + "\",this)>删除</a></td>" +
//                            "<td>"+"<a onclick=deleteFile(fileList[i].fileName)>"+"删除"+"</a>"+"</td>" +
								"</tr>";
						tbody.innerHTML = str;
					}
				}
			});
		});
		function deleteFile(fileId,obj) {
			$.ajax({
				type : "POST",
				url : "${ctx}/scene/sceneVmTemplate/uploadFileDelete",
				data : {"uploadFileId" : fileId},
				traditional : true,
				success:function(json){
					if(json.success == true){
						$(obj).parent().parent().remove();
						document.getElementById("imageId").value="";
					}
					else{
						var failMsg = json.msg;
						alertx(failMsg);
					}

				}
			})
		}
	</script>
</head>
<body>
<div id="importBox" class="hide">
	<form id="importForm" name="importForm" enctype="multipart/form-data"
		  class="form-search" style="padding-left:20px;text-align:center;"><br/>
		<input id="uploadFile" name="uploadFile" type="file" style="width:330px" onchange="picCheck(this)"/><br/><br/>　　
		<button type="button" class="btn btn-primary btnImportSubmit"> 上 传</button>
	</form>
</div>

	<ul class="nav nav-tabs">
		<li><a href="${ctx}/scene/sceneVmTemplate/">虚拟机模板列表</a></li>
		<li class="active"><a href="${ctx}/scene/sceneVmTemplate/form?id=${sceneVmTemplate.id}">虚拟机模板<shiro:hasPermission name="scene:sceneVmTemplate:edit">${not empty sceneVmTemplate.id?'修改':'添加'}</shiro:hasPermission><shiro:lacksPermission name="scene:sceneVmTemplate:edit">查看</shiro:lacksPermission></a></li>
	</ul><br/>
	<form id="inputForm" modelAttribute="sceneVmTemplate" action="${ctx}/scene/sceneVmTemplate/save" method="post" class="form-horizontal">
		<input type="hidden" id="id" name="id" value="${sceneVmTemplate.id}"/>
		<input type="hidden" id="imageName" name="imageName" value="${sceneVmTemplate.imageName}"/>

		<sys:message content="${message}"/>		
		<div class="control-group">
			<label class="control-label">虚拟机模板名称：</label>
			<div class="controls">
				<input type="text" id="name" name="name" htmlEscape="false" maxlength="64" class="input-xlarge required" value="${sceneVmTemplate.name}"/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">虚拟机模板类型：</label>
			<div class="controls">
				<select id="type" name="type" class="input-xlarge ">
					<c:choose>
						<c:when test="${isSuperAdmin=='false'}">
							<option value="0" selected>${fns:getDictLabel("0",'scene_vm_type',"无")}</option>
						</c:when>
						<c:otherwise>
							<c:forEach var="attribute" items="${fns:getDictList('scene_vm_type')}">
								<option value="${fns:getDictValue(attribute,'scene_vm_type',"")}" <c:if test="${fns:getDictValue(attribute,'scene_vm_type','')==sceneVmTemplate.type}">selected</c:if>>${attribute}</option>
							</c:forEach>
						</c:otherwise>
					</c:choose>

					<%--<form:option value="" label=""/>--%>
					<%--<form:options items="${fns:getDictList('scene_vm_type')}" itemLabel="label" itemValue="value" htmlEscape="false"/>--%>
				</select>
			</div>
		</div>
		<%--<div class="control-group">--%>
			<%--<label class="control-label">内存大小：</label>--%>
			<%--<div class="controls">--%>
				<%--<form:input path="memory" htmlEscape="false" maxlength="8" class="input-xlarge "/>--%>
			<%--</div>--%>
		<%--</div>--%>
		<%--<div class="control-group">--%>
			<%--<label class="control-label">CPU：</label>--%>
			<%--<div class="controls">--%>
				<%--<form:input path="cpu" htmlEscape="false" maxlength="64" class="input-xlarge "/>--%>
			<%--</div>--%>
		<%--</div>--%>
		<%--<div class="control-group">--%>
			<%--<label class="control-label">存储空间：</label>--%>
			<%--<div class="controls">--%>
				<%--<form:input path="storage" htmlEscape="false" maxlength="8" class="input-xlarge "/>--%>
			<%--</div>--%>
		<%--</div>--%>

		<div class="control-group">
			<label class="control-label">虚拟机镜像：</label>
			<div class="controls">
				<select id="imageRef" name="imageRef" class="input-xlarge" onchange="choose(this)">
					<option value="" selected>===请选择===</option>
					<c:forEach var="image" items="${imageList}">
						<option value="${image.id}" <c:if test="${image.id==sceneVmTemplate.imageRef}">selected</c:if>>${image.name}</option>
					</c:forEach>
				</select>

			</div>
		</div>
		<%--<div class="control-group">--%>
			<%--<label class="control-label">云主机类型：</label>--%>
			<%--<div class="controls">--%>
				<%--<select id="flavorRef" name="flavorRef" class="input-xlarge">--%>
					<%--<option value="" selected>===请选择===</option>--%>
					<%--<c:forEach var="vmType" items="${vmTypeList}">--%>
						<%--<option value="${vmType.id}" <c:if test="${vmType.id==sceneVmTemplate.flavorRef}">selected</c:if>>${vmType.name}</option>--%>
					<%--</c:forEach>--%>
				<%--</select>--%>

			<%--</div>--%>
		<%--</div>--%>
		<%--<div class="control-group">--%>
			<%--<label class="control-label">是否为操作机:</label>--%>

			<%--<div class="controls">--%>
				<%--<select id="isOperateMachine" name="isOperateMachine">--%>
					<%--<option value="" selected>===请选择===</option>--%>
					<%--<option value="0"  <c:if test="${'0'==sceneVmTemplate.isOperateMachine}">selected</c:if>>是</option>--%>
					<%--<option value="1"  <c:if test="${'1'==sceneVmTemplate.isOperateMachine}">selected</c:if>>否</option>--%>
				<%--</select>--%>
			<%--</div>--%>
		<%--</div>--%>
		<%--<div class="control-group">--%>
			<%--<label class="control-label">网络：</label>--%>
			<%--<div class="controls">--%>
				<%--<select id="networkIds" name="networkIds" class="input-xlarge">--%>
					<%--<option value="" selected>===请选择===</option>--%>
					<%--<c:forEach var="network" items="${networkList}">--%>
						<%--<option value="${network.id}" <c:if test="${network.id==sceneVmTemplate.flavorRef}">selected</c:if>>${network.networkName}</option>--%>
					<%--</c:forEach>--%>
				<%--</select>--%>

			<%--</div>--%>
		<%--</div>--%>
		<%--<div class="control-group">--%>
			<%--<label class="control-label">端口：</label>--%>
			<%--<div class="controls">--%>
				<%--<select id="portIds" name="portIds" class="input-xlarge">--%>
					<%--<option value="" selected>===请选择===</option>--%>
					<%--<c:forEach var="port" items="${portList}">--%>
						<%--<option value="${port.id}">${port.name}:${port.fixedIp}</option>--%>
					<%--</c:forEach>--%>
				<%--</select>--%>

			<%--</div>--%>
		<%--</div>--%>
		<%--<div class="control-group">--%>
			<%--<label class="control-label">安全组：</label>--%>
			<%--<div class="controls">--%>
				<%--<select id="sgIds" name="sgIds" class="input-xlarge">--%>
					<%--<option value="" selected>===请选择===</option>--%>
					<%--<c:forEach var="securityGroup" items="${securityGroupList}">--%>
						<%--<option value="${securityGroup.id}">${securityGroup.name}</option>--%>
					<%--</c:forEach>--%>
				<%--</select>--%>

			<%--</div>--%>
		<%--</div>--%>

		<div class="control-group">
			<label class="control-label">内存(MB)：</label>
			<div class="controls">
				<input type="text" id="ram" name="ram" maxlength="8" class="input-xlarge " value="${sceneVmTemplate.ram}"/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">VCPU数量：</label>
			<div class="controls">
				<input  type="text" id="vcpus" name="vcpus" maxlength="8" class="input-xlarge " value="${sceneVmTemplate.vcpus}"/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">磁盘大小(GB)：</label>
			<div class="controls">
				<input type="text" id="disk" name="disk" maxlength="8" class="input-xlarge " value="${sceneVmTemplate.disk}"/>
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">账号：</label>
			<div class="controls">
				<input type="text" id="account" name="account" maxlength="16" class="input-xlarge" value="${sceneVmTemplate.account}"  onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[\u4e00-\u9fa5]/g,''))" onkeyup="this.value=this.value.replace(/[\u4e00-\u9fa5]/g,'')" />
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">密码：</label>
			<div class="controls">
				<input type="text" id="password" name="password"  maxlength="16" class="input-xlarge" value="${sceneVmTemplate.password}"  onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/[\u4e00-\u9fa5]/g,''))" onkeyup="this.value=this.value.replace(/[\u4e00-\u9fa5]/g,'')" />
			</div>
		</div>
		<div class="control-group">
			<label class="control-label">描述：</label>
			<div class="controls">
				<textarea id="remarks" name="remarks" rows="4" maxlength="255" class="input-xxlarge ">${sceneVmTemplate.remarks}</textarea>
			</div>
		</div>
		<div class="control-group" id="imageUploadDiv">
			<label class="control-label">上传镜像：</label>
			<div class="controls">
				<input type="hidden" id="imageId" name="imageId" value="${sceneVmTemplate.imageRef}"/>
				<div class="control-group">
					<div class="controls">
						<div id="fileQueue"></div>
						<input type="file" name="uploadify" id="uploadify"  maxlength="256"/>
					</div>
					<div class="controls">
						<p>
							<a href="javascript:jQuery('#uploadify').uploadify('upload','*')">开始上传</a>
							<a href="javascript:jQuery('#uploadify').uploadify('stop')">暂停所有上传</a>
						</p>
					</div>
				</div>
				<table id="contentTable" class="table table-striped table-bordered table-condensed">
					<thead>
					<tr>
						<th>上传镜像名称</th>
						<th>操作</th>
					</tr>
					</thead>
					<tbody id="tbody-result">
						<%--<tr>--%>
							<%--<td>--%>
							<%--${sceneVmTemplate.imageName}--%>
							<%--</td>--%>
							<%--<td>--%>
								<%--&lt;%&ndash;<a href="#" onclick="deleteFile('${sceneVmTemplate.imageName}',this)">删除</a>&ndash;%&gt;--%>
							<%--</td>--%>
						<%--</tr>--%>
					</tbody>
				</table>
			</div>
		</div>

		<%--<div class="control-group"  id="imageUploadDiv">--%>
			<%--<label class="control-label">上传镜像：</label>--%>
			<%--<div class="controls">--%>
				<%--<input type="hidden" name="imageId" id="imageId" htmlEscape="false" maxlength="256" class="input-xlarge" readonly="true" value="${coursewareDocumentIds}"/>--%>
				<%--<input type="text" name="imageUrl" id="imageUrl" htmlEscape="false" maxlength="256" class="input-xlarge" value="${coursewareDocumentURL}" readonly="true"/>--%>
				<%--<input id="imageUpload" class="btn btn-primary" type="button" value="上传"/>--%>
			<%--</div>--%>
		<%--</div>--%>
		<div class="form-actions">
			<shiro:hasPermission name="scene:sceneVmTemplate:edit"><input id="btnSubmit" class="btn btn-primary" type="submit" value="保 存" onclick=" return checkValidate()"/>&nbsp;</shiro:hasPermission>
			<input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)"/>
		</div>
	</form>
</body>
</html>